import os.path,json,os



def __find_fp__(fn):
    # test目录程序运行时 database.json 路径
    if os.path.exists(f'../../{fn}'):
        return f'../../{fn}'
    # acad_horizon_spiders目录运行spider时 database.json 路径
    elif os.path.exists(f'../{fn}'):
        return f'../../{fn}'
    # acad_horizon_spiders/acad_horizon_spiders目录运行spider时 database.json 路径
    elif os.path.exists(f'{fn}'):
        return f'{fn}'
    
    with open(fn, 'w') as file:
        file.write("{}")
        file.close()
    return f'{fn}'





""" 
    获取数据库所有数据，以字典返回
"""
def get_alldata(fn="database.json") -> dict:
    fp=__find_fp__(fn)
    file = open(fp,'r',encoding='UTF-8')  
    js = json.load(file)
    file.close()
    return js

""" 
    查找key的value值，并返回
"""
def get_value(key:str,fn="database.json")-> any:
    fp=__find_fp__(fn)
    js=get_alldata()
    return js.get(key)

""" 
    查找多个key的value值，并以字典返回
"""
def get_dict(fn="database.json",*keys):
    fp=__find_fp__(fn)
    js=get_alldata()
    d= dict()
    for key in keys:
        d[key]=js[key]
    return d
""" 
    删除多个key的value值
"""
def delete(fn="database.json",*keys):
    fp=__find_fp__(fn)
    js=get_alldata()
    for key in keys:
        js.pop(key)
    file = open(fp,'w',encoding='UTF-8')  
    json.dump(js,file,ensure_ascii=False,indent=2)
    file.close()


""" 
输入 dict 或 键值对
example update({1:1}) 或 update(key,value)

"""
def update(fn="database.json",*args):
    fp=__find_fp__(fn)
    js=get_alldata(fp)
    file = open(fp,'w',encoding='UTF-8')  
    if  len(args)==1:
        js.update(args[0])
    elif len(args)==2:
        # js.update()
        js[args[0]]=args[1]
    json.dump(js,file,ensure_ascii=False,indent=2)
    file.close()


def update_list(fn="database.json",*args):
    fp=fn
    js=get_alldata(fp)
    file = open(fp,'w',encoding='UTF-8')  
    if  len(args)==1:
        js.update(args[0])
    elif len(args)==2:
        # js.update()
        # js
        if js.get(args[0])==None:
            js[args[0]]=args[1]
        else:    
            js[args[0]]=js[args[0]]+args[1]
    # js[args[0]] = sorted(js[args[0]], key=lambda x: x['id'])
    json.dump(js,file,ensure_ascii=False,indent=2)
    file.close()


